import { Component, OnInit } from '@angular/core';
import { NzModalService, NzMessageService } from 'ng-zorro-antd';
import { _HttpClient } from '@core/services/http.client';
import { FormGroup, FormBuilder, Validators, FormControl, AsyncValidatorFn, AbstractControl } from '@angular/forms';
import { Observable } from 'rxjs/Observable';
import { Router } from '@angular/router';
import { TokenService } from "@core/net/token/token.service";
import * as moment from 'moment';
import { TokenData } from "@core/net/token/token.type";
import { HttpService } from "@core/services/http.service";
import swal from "sweetalert2";

@Component({
    selector: 'app-school',
    templateUrl: './school.component.html',
    styles: [`
        :host ::ng-deep  .ant-modal{
            top: 100px !important;
        }
    `]
})

export class SchoolComponent implements OnInit {
    selectValue1;
    selectValue2;
    popTitle;
    loading = false;
    modalVisible2 = false;
    S_id = '';
    Sname = '';
    Sgly = '';
    SglyPass = '';
    Stel = '';
    Province = '';
    City = '';
    _allChecked = false;
    _indeterminate = false;
    _displayData = [];
    _checkTable = [];
    _checkLength = 0;
    _q = { pi: 1, ps: 10 };

    saveState = '';
    searchValue = '';
    serchName = {};
    ids = [];
    _loading = false;
    formNews = {};
    data = [];
    Status = [];
    sta = '';
    param: any;

    form: FormGroup;
    xxName: any;
    xyName: any;
    glyName: any;
    pass: any;
    tel: any;
    province = ["北京", "天津", "上海", "重庆", "河北", "山西", "辽宁", "吉林", "黑龙江", "江苏", "浙江", "安徽", "福建", "江西", "山东", "河南", "湖北", "湖南", "广东", "海南", "四川", "贵州", "云南", "陕西", "甘肃", "青海", "内蒙古", "广西", "西藏", "宁夏", "新疆维吾尔自治区", "香港", "澳门", "台湾"];
    city = { 北京: ["北京"], 天津: ["天津"], 上海: ["上海"], 重庆: ["重庆"], 河北: ["石家庄", "唐山", "秦皇岛", "邯郸", "邢台", "保定", "张家口", "承德", "沧州", "廊坊", "衡水"], 山西: ["太原", "大同", "阳泉", "长治", "晋城", "朔州", "晋中", "运城", "忻州", "临汾", "吕梁"], 辽宁: ["沈阳", "大连", "鞍山", "抚顺", "本溪", "丹东", "锦州", "营口", "阜新", "辽阳", "盘锦", "铁岭", "朝阳", "葫芦岛"], 吉林: ["长春", "吉林", "四平", "辽源", "通化", "白山", "松原", "白城", "延边朝鲜族自治州"], 黑龙江: ["哈尔滨", "齐齐哈尔", "鹤岗", "双鸭山", "鸡西", "大庆", "伊春", "牡丹江", "佳木斯", "七台河", "黑河", "绥化", "大兴安岭"], 江苏: ["南京", "苏州", "无锡", "常州", "镇江", "南通", "泰州", "扬州", "盐城", "连云港", "徐州", "淮安", "宿迁"], 浙江: ["杭州", "宁波", "温州", "嘉兴", "湖州", "绍兴", "金华", "衢州", "舟山", "台州", "丽水"], 安徽: ["合肥", "芜湖", "蚌埠", "淮南", "马鞍山", "淮北", "铜陵", "安庆", "黄山", "滁州", "阜阳", "宿州", "巢湖", "六安", "亳州", "池州", "宣城"], 福建: ["福州", "厦门", "莆田", "三明", "泉州", "漳州", "南平", "龙岩", "宁德"], 江西: ["南昌", "景德镇", "萍乡", "九江", "新余", "鹰潭", "赣州", "吉安", "宜春", "抚州", "上饶"], 山东: ["济南", "青岛", "淄博", "枣庄", "东营", "烟台", "潍坊", "济宁", "泰安", "威海", "日照", "莱芜", "临沂", "德州", "聊城", "滨州", "菏泽"], 河南: ["郑州", "开封", "洛阳", "平顶山", "安阳", "鹤壁", "新乡", "焦作", "濮阳", "许昌", "漯河", "三门峡", "南阳", "商丘", "信阳", "周口", "驻马店"], 湖北: ["武汉", "黄石", "十堰", "荆州", "宜昌", "襄樊", "鄂州", "荆门", "孝感", "黄冈", "咸宁", "随州", "恩施"], 湖南: ["长沙", "株洲", "湘潭", "衡阳", "邵阳", "岳阳", "常德", "张家界", "益阳", "郴州", "永州", "怀化", "娄底", "湘西"], 广东: ["广州", "深圳", "珠海", "汕头", "韶关", "佛山", "江门", "湛江", "茂名", "肇庆", "惠州", "梅州", "汕尾", "河源", "阳江", "清远", "东莞", "中山", "潮州", "揭阳", "云浮"], 海南: ["海口", "三亚"], 四川: ["成都", "自贡", "攀枝花", "泸州", "德阳", "绵阳", "广元", "遂宁", "内江", "乐山", "南充", "眉山", "宜宾", "广安", "达州", "雅安", "巴中", "资阳", "阿坝", "甘孜", "凉山"], 贵州: ["贵阳", "六盘水", "遵义", "安顺", "铜仁", "毕节", "黔西南", "黔东南", "黔南"], 云南: ["昆明", "曲靖", "玉溪", "保山", "昭通", "丽江", "普洱", "临沧", "德宏", "怒江", "迪庆", "大理", "楚雄", "红河", "文山", "西双版纳"], 陕西: ["西安", "铜川", "宝鸡", "咸阳", "渭南", "延安", "汉中", "榆林", "安康", "商洛"], 甘肃: ["兰州", "嘉峪关", "金昌", "白银", "天水", "武威", "酒泉", "张掖", "庆阳", "平凉", "定西", "陇南", "临夏", "甘南"], 青海: ["西宁", "海东", "海北", "海南", "黄南", "果洛", "玉树", "海西"], 内蒙古: ["呼和浩特", "包头", "乌海", "赤峰", "通辽", "鄂尔多斯", "呼伦贝尔", "巴彦淖尔", "乌兰察布", "锡林郭勒盟", "兴安盟", "阿拉善盟"], 广西: ["南宁", "柳州", "桂林", "梧州", "北海", "防城港", "钦州", "贵港", "玉林", "百色", "贺州", "河池", "来宾", "崇左"], 西藏: ["拉萨", "那曲", "昌都", "林芝", "山南", "日喀则", "阿里"], 宁夏: ["银川", "石嘴山", "吴忠", "固原", "中卫"], 新疆维吾尔自治区: ["乌鲁木齐", "克拉玛依", "吐鲁番", "哈密", "和田", "阿克苏", "喀什", "克孜勒苏", "巴音郭楞", "昌吉", "博尔塔拉", "伊犁", "塔城", "阿勒泰"], 香港: ["香港"], 澳门: ["澳门"], 台湾: ["台北", "高雄", "基隆", "新竹", "台中", "嘉义", "台南"] };
    cityArr = [];
    key = '';
    cloubModal = false;
    CourseModal = false;
    cloudList = [];
    cloubTotal;
    cloudArr = [];
    sch_id;
    courseArr = [];
    courseTotal;
    courseList = [];

    style = {
        width: '70%',
        top: '0px'
    };

    clock(data) {
        let title;
        let isuse;
        let http = this.http;
        let that = this;
        if (data.IsUse == 0) {
            // 未锁定
            title = '您是否要锁定这个学校';
            isuse = 1;
        } else {
            // 锁定
            title = '您是否要解锁这个学校';
            isuse = 0;
        }
        this.confirmServ.confirm({
            title: title,
            content: '',
            okText: '确定',
            cancelText: '取消',
            onOk() {
                http.isUser({ use: isuse, u_id: data.Id }).subscribe(res => {
                    if (res['code'] == 0) {
                        that.getData()
                    }
                    swal(res['msg'], '', 'info');
                })
            },
            onCancel() {

            }
        });
    }
    formreset(event) {
        this.modalVisible2 = false;
        event.preventDefault();
        this.form.reset();
        for (const key in this.form.controls) {
            this.form.controls[key].markAsPristine();
        }
    }
    getFormControl(name) {
        return this.form.controls[name];
    }

    ngOnInit() {
        this.form = this.fb.group({
            // email: [null, [Validators.email]],
            xxName: [null, [Validators.required]],
            proName: [null],
            cityName: [null],
            glyName: [null, [Validators.required]],
            pass: [null, [Validators.required]],
            tel: [null, [Validators.required, Validators.email]]
            // phoneNumberPrefix: ['+86', [Validators.required]]
        }, );
        this.getData();
    }

    getData() {
        this.param = {
            // State: 1,
            // Role: this.token.data.role,
            // Condition: this.searchValue
            key: this.key
        };
        this.loading = true;
        this.http.getSchoolList(this.param).subscribe(res => {
            this.data = res['list'];

        });
        this.loading = false;
        // this.Province = this.province[0]
        // this.cityArr = this.city[this.Province];
        // this.City = this.cityArr[0];
    }
    proChange() {
        this.cityArr = this.city[this.Province];
        if (this.cityArr) {
            this.City = this.cityArr[0]
        }
    }
    save() {
        for (const i in this.form.controls) {
            this.form.controls[i].markAsDirty();
        }
        if (this.form.valid) {
            this.loading = true;
            if (this.saveState === 'add') {

                this.param = {
                    LoginName: this.form.value.glyName,
                    LoginPwd: this.form.value.pass,
                    ContactWay: this.form.value.tel,
                    Type: '2',
                    sch_id: '',
                    UserName: this.form.value.glyName + '-管理员',
                    SchoolName: this.form.value.xxName,
                    Province: this.form.value.proName,
                    City: this.form.value.cityName
                }
                this.http.SaveSchool(this.param).subscribe(res => {
                    if (res['code'] == '0') {
                        this.msgService.success(res['msg']);
                        // this.router.navigate(['home']);
                        this.getData();
                        this.modalVisible2 = false;
                    } else {
                        this.msgService.error(res['msg']);
                    }
                });
            } else {
                this.param = {
                    sch_id: this.S_id,
                    UserName: this.form.value.glyName + '-管理员',
                    LoginName: this.form.value.glyName,
                    LoginPwd: this.form.value.pass,
                    ContactWay: this.form.value.tel,
                    Type: '2',
                    SchoolName: this.form.value.xxName,
                    Province: this.form.value.proName,
                    City: this.form.value.cityName
                }
                this.http.SaveSchool(this.param).subscribe(res => {
                    if (res['code'] == '0') {
                        this.msgService.success(res['msg']);
                        this.getData();
                        this.modalVisible2 = false;
                    } else {
                        this.msgService.error(res['msg']);
                    }
                });
            }
            this.loading = false;
        }
    }

    modal(state, data) {
        let val = document.querySelectorAll('.ant-select-selection-selected-value');
        if (state === 'add') {
            this.modalVisible2 = true;
            this.Sname = '';
            this.Province = '';
            this.City = '';
            this.Sgly = '';
            this.SglyPass = '';
            this.Stel = '';
            this.popTitle = '新建学校信息';
            this.saveState = 'add';
        } else if (state === 'update') {
            this.modalVisible2 = true;
            this.popTitle = '修改学校信息';
            this.S_id = data.sch_id;
            this.Sname = data.SchoolName;
            this.Province = data.Province;
            this.City = data.City;
            this.Sgly = data.LoginName;
            this.SglyPass = data.LoginPwd;
            this.Stel = data.ContactWay;
            this.saveState = 'update';
        }
        // val[0].innerHTML= this.Province;
        // val[1].innerHTML= this.City;
    }

    search() {
        this.key = this.searchValue;
        this.getData();
        // this.serchName = {name: this.searchValue}
        // this.http.post('', this.serchName).subscribe(res => {
        //     console.log(res);
        // });
    }

    showConfirm = (data) => {
        let context = this;
        let http = this.http;
        let msgService = this.msgService;
        this.confirmServ.confirm({
            title: '您是否确认要删除这项内容',
            content: '',
            okText: '确定',
            cancelText: '取消',
            onOk() {
                const id = { sch_id: data.sch_id };
                context.loading = true;
                http.deleteSchool(id).subscribe(res => {
                    if (res['code'] == '0') {
                        msgService.success(res['msg']);
                        context.getData();
                        context = null;
                        // this.router.navigate(['home']);
                    } else {
                        msgService.error(res['msg']);
                    }
                });
                context.loading = false;
            },
            onCancel() {
            }
        });
    }

    _displayDataChange($event) {
        this._displayData = $event;
        this._refreshStatus();
    }

    _refreshStatus() {
        const allChecked = this._displayData.every(value => value.checked === true);
        const allUnChecked = this._displayData.every(value => !value.checked);
        const checkTable = this._displayData.filter(value => value.checked);
        this._allChecked = allChecked;
        this._indeterminate = (!allChecked) && (!allUnChecked);
        this._checkTable = checkTable;
        this._checkLength = checkTable.length;
    }

    _checkAll(value) {
        if (value) {
            this._displayData.forEach(data => {
                data.checked = true;
            });
        } else {
            this._displayData.forEach(data => {
                data.checked = false;
            });
        }
        this._refreshStatus();
    }

    allDelete() {
        let context = this;
        let http = this.http;
        let msgService = this.msgService;
        this._checkTable.map(m => {
            this.ids.push(m.id);
        });
        this.confirmServ.confirm({
            title: '您是否确认要批量删除选中的' + this._checkLength + '项内容？',
            content: '',
            okText: '确定',
            cancelText: '取消',
            onOk: () => {
                const id = { id: this.ids.toString() };
                context.loading = true;
                http.userDel(id).subscribe(res => {
                    if (res['code'] == '0') {
                        msgService.success(res['msg']);
                        context.getData();
                        context = null;
                        // this.router.navigate(['home']);
                    } else {
                        msgService.error(res['msg']);
                    }
                });
                context.loading = false;
            },
            onCancel() {
            }
        });
    }

    info(contentTpl, data, status) {
        this.Sname = data.SchoolName;
        this.Province = data.Province;
        this.City = data.City;
        this.Sgly = data.LoginName;
        this.Stel = data.ContactWay;
        this.confirmServ.info({
            title: '查看详情',
            content: contentTpl,
            okText: '确定'
        });
    }

    constructor(
        private confirmServ: NzModalService,
        // private http: _HttpClient,
        private _message: NzMessageService,
        private fb: FormBuilder,
        private msg: NzMessageService,
        private http: HttpService,
        private token: TokenService,
        private router: Router,
        private msgService: NzMessageService
    ) {
        /*  email: [null, Validators.compose([Validators.required])],
              password: [null, Validators.required],
              remember_me: [null]*/
    }


    cloudProject(data) {
        //console.log(data)
        this.cloudArr = [];
        this.sch_id = data.sch_id
        this.cloubModal = true
        this.http.getProject('cloud', { pi: 1, ps: 9999 }).then(res => {
            // console.log(res)
            this.cloudList = res['list'];
            this.cloubTotal = res['total'];
            this.http.getCloudListBySchId({ sch_id: data.sch_id }).subscribe(data => {
                //console.log(data)
                let tlist = data['list'];
                for (let list of this.cloudList) {
                    list['isCheck'] = false;
                    for (let cli of tlist) {
                        if (list.p_id == cli.cloud_id) {
                            this.cloudArr.push(list.p_id);
                            list.isCheck = true
                        }
                    }
                }
            })
        });
    }

    cloudChange(event, p_id) {
        if (event) {
            this.cloudArr.push(p_id);
        } else {
            this.removeByValue(this.cloudArr, p_id);
        }
    }

    SaveCloudSchool() {
        this.http.SaveCloudSchool({ sch_id: this.sch_id, cloudArr: this.cloudArr }).subscribe(res => {
            // console.log(res)
            swal(res['msg'], '', 'info');
            this.cloubModal = false;
        });
    }


    CrouseProject(data) {
        // console.log(data)
        this.courseArr = [];
        this.sch_id = data.sch_id;
        this.CourseModal = true;
        this.http.getCourse({ pi: 1, ps: 9999, key: '' }).subscribe(res => {
            // console.log(res)
            this.courseList = res['list'];
            this.courseTotal = res['total'];
            this.http.getCourseListBySchId({ sch_id: data.sch_id }).subscribe(data => {
                // console.log(data)
                let tlist = data['list'];
                for (let list of this.courseList) {
                    list['isCheck'] = false;
                    for (let cli of tlist) {
                        if (list.cour_id == cli.course_pid) {
                            this.courseArr.push(list.cour_id);
                            list.isCheck = true;
                        }
                    }
                }
            });
        });
    }

    SaveCourseSchool() {
        this.http.SaveCousrseSchool({ sch_id: this.sch_id, cArr: this.courseArr }).subscribe(res => {
            // console.log(res)
            swal(res['msg'], '', 'info');
            this.CourseModal = false;
        });
    }

    CourseChange(event, cour_id) {
        if (event) {
            this.courseArr.push(cour_id);
        } else {
            this.removeByValue(this.courseArr, cour_id);
        }
    }

    removeByValue(arr, val) {
        for (var i = 0; i < arr.length; i++) {
            if (arr[i] == val) {
                arr.splice(i, 1);
                break;
            }
        }
    }
}
